package ReflectDemo;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//反射操作注解
public class Test12 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("ReflectDemo.Stud");

        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获得注解的value的值
        TableAnnotation annotation = (TableAnnotation) c1.getAnnotation(TableAnnotation.class);
        String value = annotation.value();
        System.out.println(value);

        //获得类指定的注解
        Field name = c1.getDeclaredField("name");
        FiledAnnotation annotation1 = name.getAnnotation(FiledAnnotation.class);
        System.out.println(annotation1.columnName());
        System.out.println(annotation1.type());
        System.out.println(annotation1.length());
    }
}


@TableAnnotation("db_student")
class Stud{
    @FiledAnnotation(columnName ="db_id",type = "int", length = 10)
    private int id;
    @FiledAnnotation(columnName = "db_name",type = "varchar",length = 10)
    private String name;
    @FiledAnnotation(columnName = "db_age", type = "int" , length = 3)
    private int age;

    public Stud() {
    }

    public Stud(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Stud{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableAnnotation{
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FiledAnnotation{
    String columnName();
    String type();
    int length();
}